package xin.infinite.service;



import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.data.domain.Example;
import org.springframework.util.CollectionUtils;
import xin.infinite.dao.CodeDao;
import xin.infinite.entity.Code;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@org.springframework.stereotype.Service
public class CodeServiceImpl implements CodeService {

    private static Random random=new Random();

    @Autowired
    private CodeDao codeDao;


    @Reference(check = true)
    private MailService mailService;

    @Reference(check = false)
    private UserServiceDubbo userService;


    @Override
    public boolean create(String email) {
        if(StringUtils.isBlank(email)){
            return false;
        }
        if(userService.isRegister(email)){
            System.out.println("该邮箱已被注册！");
            return false;
        }
        StringBuffer stringBuffer=new StringBuffer();
        for (int i = 0; i < 4; i++) {
            stringBuffer.append(random.nextInt(9));
        }
        String codeStr=stringBuffer.toString();
        Code code=new Code();
        code.setEmail(email);
        List<Code> all = codeDao.findAll(Example.of(code));
        if(!CollectionUtils.isEmpty(all)&&all.size()==1){
            code=all.get(0);
        }
        code.setCode(codeStr);
        Date createtime=new Date();
        System.out.println("验证码为"+codeStr);
        System.out.println("创建日期为"+createtime);
        code.setCreatetime(createtime);
        codeDao.save(code);
        //发送邮件
        mailService.sendCodeEmail(email,codeStr);
        return true;
    }

    @Override
    public int isCorrect(String email,String code) {
        if(StringUtils.isBlank(email)){
            return 1;
        }
        Code entity=new Code();
        entity.setEmail(email);
        entity.setCode(code);
        List<Code> all = codeDao.findAll(Example.of(entity));
        if(!CollectionUtils.isEmpty(all)&&all.size()==1){
            entity=all.get(0);
            Date now=new Date();
            Date createtime = entity.getCreatetime();
            if((now.getTime()-createtime.getTime())/1000/60<10){
                return 0;
            }else {
                return 2;
            }
        }
        return 1;
    }
}
